package com.atguigu.flink.chapter06.timer;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2023/6/21 14:34
 */
public class TimerTest {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 如果水位连续5s 超过 20,则发出红色预警
        // 当第一个超过 20 的来的时候, 注册定时器 5s 触发, 如果后面来的都是>20 的,则无需操作,一旦出现小于等于 20 的则,取消定时器
        env.socketTextStream("hadoop162", 8888)
            .map(new WaterSensorMapFunction())
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forMonotonousTimestamps()
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            )
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                // 当定时器触发的时候,会回调这个方法
                @Override
                public void onTimer(long timestamp, // 定时器时间
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    
                    
                    out.collect("水位连续 5s 超过 20, 发出预警...." + timestamp);
                    isFirst20 = true;
                }
                
               
                boolean isFirst20 = true;
                long timerTs;
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    
                    if (value.getVc() > 20 && isFirst20) {
                        isFirst20 = false;
                        // 注册一个 4s 后触发的定时器
                        timerTs = value.getTs() + 5000;
                        System.out.println("第一个大于 20 的来了,注册定时器: " + timerTs);
                        ctx.timerService().registerEventTimeTimer(timerTs);
                    }else if(value.getVc() < 20){
                        System.out.println("取消定时器: " + timerTs);
                        ctx.timerService().deleteEventTimeTimer(timerTs);
                        // 把 isFirst 置为 true
                        isFirst20 = true;
                    }
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
